import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../components"
import "../dialogs"

/**
 * 设备管理页面
 * 功能：设备列表展示、添加/编辑/删除设备、连接/断开设备
 */
Item {
    id: root
    
    // ========================================
    // 主布局
    // ========================================
    ColumnLayout {
        anchors.fill: parent
        anchors.margins: 20
        spacing: 20
        
        // ========================================
        // 顶部工具栏
        // ========================================
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 80
            color: "white"
            radius: 10
            
            // 阴影效果（简化版）
            layer.enabled: true
            
            RowLayout {
                anchors.fill: parent
                anchors.margins: 20
                spacing: 15
                
                // 左侧：操作按钮
                RowLayout {
                    spacing: 10
                    
                    // 添加设备按钮
                    Button {
                        text: "➕ 添加设备"
                        
                        Layout.preferredHeight: 40
                        
                        background: Rectangle {
                            color: parent.hovered ? "#2563eb" : "#3b82f6"
                            radius: 8
                            
                            Behavior on color {
                                ColorAnimation { duration: 150 }
                            }
                        }
                        
                        contentItem: Text {
                            text: parent.text
                            font.pixelSize: 15
                            font.bold: true
                            color: "white"
                            horizontalAlignment: Text.AlignHCenter
                            verticalAlignment: Text.AlignVCenter
                        }
                        
                        onClicked: {
                            addDeviceDialog.open()
                        }
                    }
                    
                    // 刷新按钮
                    Button {
                        text: "🔄 刷新"
                        
                        Layout.preferredHeight: 40
                        
                        background: Rectangle {
                            color: parent.hovered ? "#f3f4f6" : "white"
                            border.color: "#d1d5db"
                            border.width: 2
                            radius: 8
                            
                            Behavior on color {
                                ColorAnimation { duration: 150 }
                            }
                        }
                        
                        contentItem: Text {
                            text: parent.text
                            font.pixelSize: 15
                            color: "#666"
                            horizontalAlignment: Text.AlignHCenter
                            verticalAlignment: Text.AlignVCenter
                        }
                        
                        onClicked: {
                            deviceModel.loadFromDatabase()
                            console.log("设备列表已刷新")
                        }
                    }
                }
                
                Item { Layout.fillWidth: true }
                
                // 右侧：统计信息
                RowLayout {
                    spacing: 20
                    
                    // 在线设备数
                    Row {
                        spacing: 8
                        
                        Rectangle {
                            width: 12
                            height: 12
                            radius: 6
                            color: "#10b981"
                            anchors.verticalCenter: parent.verticalCenter
                            
                            SequentialAnimation on opacity {
                                running: true
                                loops: Animation.Infinite
                                NumberAnimation { from: 1.0; to: 0.3; duration: 1000 }
                                NumberAnimation { from: 0.3; to: 1.0; duration: 1000 }
                            }
                        }
                        
                        Text {
                            text: "在线: " + getOnlineCount()
                            font.pixelSize: 16
                            font.bold: true
                            color: "#10b981"
                            anchors.verticalCenter: parent.verticalCenter
                        }
                    }
                    
                    // 分隔线
                    Rectangle {
                        width: 1
                        height: 30
                        color: "#e5e7eb"
                    }
                    
                    // 总设备数
                    Row {
                        spacing: 8
                        
                        Text {
                            text: "📊"
                            font.pixelSize: 16
                            anchors.verticalCenter: parent.verticalCenter
                        }
                        
                        Text {
                            text: "总计: " + deviceModel.count
                            font.pixelSize: 16
                            color: "#666"
                            anchors.verticalCenter: parent.verticalCenter
                        }
                    }
                }
            }
        }
        
        // ========================================
        // 设备列表区域
        // ========================================
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "white"
            radius: 10
            
            layer.enabled: true
            
            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 20
                spacing: 0
                
                // 列表标题
                Text {
                    text: deviceModel.count > 0 ? "设备列表 (" + deviceModel.count + ")" : "设备列表"
                    font.pixelSize: 18
                    font.bold: true
                    color: "#333"
                    Layout.bottomMargin: 15
                }
                
                // 设备列表（或空状态）
                Item {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    
                    // 设备列表
                    ListView {
                        id: deviceListView
                        visible: deviceModel.count > 0
                        anchors.fill: parent
                        model: deviceModel
                        spacing: 15
                        clip: true
                        
                        // 滚动条
                        ScrollBar.vertical: ScrollBar {
                            policy: ScrollBar.AsNeeded
                        }
                        
                        // 设备列表项委托
                        delegate: DeviceListItem {
                            width: deviceListView.width - 20
                            
                            deviceId: model.deviceId
                            deviceName: model.deviceName
                            ipAddress: model.ipAddress
                            port: model.port
                            slaveId: model.slaveId
                            status: model.status
                            lastUpdate: model.lastUpdate
                            description: model.description
                            
                            // 连接设备
                            onConnectClicked: {
                                console.log("连接设备:", deviceId)
                                if (modbusController.connectToDevice(deviceId)) {
                                    console.log("✓ 开始连接设备:", deviceId)
                                } else {
                                    console.error("✗ 连接设备失败:", deviceId)
                                }
                            }
                            
                            // 断开设备
                            onDisconnectClicked: {
                                console.log("断开设备:", deviceId)
                                confirmDialog.showConfirm(
                                    "断开设备",
                                    "确定要断开设备 " + deviceName + " 的连接吗？",
                                    function() {
                                        modbusController.disconnectFromDevice(deviceId)
                                        console.log("✓ 已断开设备:", deviceId)
                                    }
                                )
                            }
                            
                            // 查看数据（跳转到仪表盘）
                            onViewDataClicked: {
                                console.log("查看设备数据:", deviceId)
                                modbusController.switchToDevice(deviceId)
                                // 跳转到仪表盘页面
                                // mainWindow.switchToPage("dashboard")
                            }
                            
                            // 编辑设备
                            onEditClicked: {
                                console.log("编辑设备:", deviceId)
                                editDeviceDialog.loadDevice(
                                    deviceId,
                                    deviceName,
                                    ipAddress,
                                    port,
                                    slaveId,
                                    description
                                )
                                editDeviceDialog.open()
                            }
                            
                            // 删除设备
                            onDeleteClicked: {
                                console.log("删除设备:", deviceId)
                                confirmDialog.showDanger(
                                    "删除设备",
                                    "确定要删除设备 " + deviceName + " 吗？\n此操作不可恢复！",
                                    function() {
                                        if (deviceModel.removeDevice(deviceId)) {
                                            console.log("✓ 设备删除成功:", deviceId)
                                        } else {
                                            console.error("✗ 设备删除失败:", deviceId)
                                        }
                                    }
                                )
                            }
                        }
                    }
                    
                    // 空状态提示
                    ColumnLayout {
                        visible: deviceModel.count === 0
                        anchors.centerIn: parent
                        spacing: 20
                        
                        Text {
                            text: "📭"
                            font.pixelSize: 64
                            Layout.alignment: Qt.AlignHCenter
                        }
                        
                        Text {
                            text: "暂无设备"
                            font.pixelSize: 20
                            font.bold: true
                            color: "#9ca3af"
                            Layout.alignment: Qt.AlignHCenter
                        }
                        
                        Text {
                            text: "点击「添加设备」按钮添加第一台设备"
                            font.pixelSize: 14
                            color: "#9ca3af"
                            Layout.alignment: Qt.AlignHCenter
                        }
                        
                        Button {
                            text: "➕ 添加设备"
                            
                            Layout.alignment: Qt.AlignHCenter
                            Layout.preferredWidth: 150
                            Layout.preferredHeight: 45
                            
                            background: Rectangle {
                                color: parent.hovered ? "#2563eb" : "#3b82f6"
                                radius: 8
                                
                                Behavior on color {
                                    ColorAnimation { duration: 150 }
                                }
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                font.pixelSize: 16
                                font.bold: true
                                color: "white"
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                            
                            onClicked: {
                                addDeviceDialog.open()
                            }
                        }
                    }
                }
            }
        }
    }
    
    // ========================================
    // 对话框组件
    // ========================================
    
    // 添加设备对话框
    AddDeviceDialog {
        id: addDeviceDialog
        parent: Overlay.overlay
        
        onDeviceAdded: {
            console.log("添加设备:", deviceId, deviceName, ipAddress, port, slaveId)
            
            // 检查设备 ID 是否已存在
            if (deviceModel.deviceExists(deviceId)) {
                confirmDialog.showInfo(
                    "添加失败",
                    "设备 ID " + deviceId + " 已存在，请使用其他 ID"
                )
                return
            }
            
            // 添加设备到数据库
            if (deviceModel.addDevice(deviceId, deviceName, ipAddress, port, slaveId, description)) {
                console.log("✓ 设备添加成功:", deviceId)
                confirmDialog.showInfo(
                    "添加成功",
                    "设备 " + deviceName + " 已成功添加"
                )
            } else {
                console.error("✗ 设备添加失败:", deviceId)
                confirmDialog.showInfo(
                    "添加失败",
                    "设备添加失败，请检查输入信息"
                )
            }
        }
    }
    
    // 编辑设备对话框
    EditDeviceDialog {
        id: editDeviceDialog
        parent: Overlay.overlay
        
        onDeviceUpdated: {
            console.log("更新设备:", deviceId, deviceName, ipAddress, port, slaveId)
            
            // 更新设备信息
            if (deviceModel.updateDevice(deviceId, deviceName, ipAddress, port, slaveId, description)) {
                console.log("✓ 设备更新成功:", deviceId)
                confirmDialog.showInfo(
                    "更新成功",
                    "设备 " + deviceName + " 信息已更新"
                )
            } else {
                console.error("✗ 设备更新失败:", deviceId)
                confirmDialog.showInfo(
                    "更新失败",
                    "设备信息更新失败"
                )
            }
        }
    }
    
    // 通用确认对话框（使用全局对话框）
    ConfirmDialog {
        id: confirmDialog
        parent: Overlay.overlay
    }
    
    // ========================================
    // 监听 Modbus 控制器信号
    // ========================================
    Connections {
        target: modbusController
        
        function onDeviceConnected(deviceId) {
            console.log("设备已连接:", deviceId)
            deviceModel.updateDeviceStatus(deviceId, "online")
        }
        
        function onDeviceDisconnected(deviceId) {
            console.log("设备已断开:", deviceId)
            deviceModel.updateDeviceStatus(deviceId, "offline")
        }
        
        function onDeviceConnectionFailed(deviceId, error) {
            console.error("设备连接失败:", deviceId, error)
            deviceModel.updateDeviceStatus(deviceId, "error")
            confirmDialog.showInfo(
                "连接失败",
                "设备连接失败：" + error
            )
        }
    }
    
    // ========================================
    // JavaScript 函数
    // ========================================
    
    // 获取在线设备数量（直接调用 C++ 方法）
    function getOnlineCount() {
        return deviceModel.getOnlineCount()
    }
    
    // ========================================
    // 组件完成
    // ========================================
    Component.onCompleted: {
        console.log("✅ DeviceManagePage 加载完成")
        console.log("  - 设备数量:", deviceModel.count)
        
        // 刷新设备列表
        deviceModel.loadFromDatabase()
    }
}

